<template>
    <el-card shadow="never">
        <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" show-icon :closable="false"></el-alert>

        <el-row class="cate-list">
            <el-col>
                <span>选择商品分类：</span>
                <el-cascader v-model="cat_info" :options="options" :props="props" @change="handleChange" :clearable="true"
                    placeholder="请选择">
                </el-cascader>
            </el-col>
        </el-row>
    </el-card>
    <!-- { value: 'cat_id',label: 'cat_name',children: 'children'} -->
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
            <el-button type="primary" :disabled="btnDisabled" @click="addFormVisible = true">添加参数</el-button>
            <el-table :data="tableData"   style="width: 100%" row-key="attr_id" :expand-row-key="expArr"
                @expand-change="expandchange">
                <el-table-column type="expand">
                    <template #default="scope">
                        <el-tag v-for="item, index in scope.row.attr_vals" :ket="index" closable @close="removeTag(scope.row, index
                        )">
                            {{ item }}
                        </el-tag>
                        <el-input v-if="scope.row.inputVisible" ref="InputRef" v-model="scope.row.inputValue"
                            class="w-1 m-1" size="small" @keyup.enter="handleInputConfirm(scope.row)"
                            @blur="handleInputConfirm(scope.row)" />
                        <el-button v-else class="m-1" size="small" @click="showInput(scope.row)">
                            + New Tag
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="index" label="#" width="180" />
                <el-table-column prop="attr_name" label="属性名称">
                </el-table-column>
                <el-table-column>
                    <template #default="scope">
                        <el-button type="primary" :icon="EditOutlined" size="small"
                            @click="editshow(scope.row)">编辑</el-button>
                        <el-button type="danger" :icon="DeleteOutlined" size="small"
                            @click="del(scope.row.attr_id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-tab-pane>


        <el-tab-pane label="静态属性" name="only">
            <el-button type="primary" :disabled="btnDisabled" @click="addFormVisible = true"> 添加属性</el-button>
            <el-table :data="tableData"  style="width: 100%"  row-key="attr_id" :expand-row-key="expArr" @expand-change="expandchange">
                <el-table-column type="expand">
                    <template #default="scope">
                        <el-tag v-for="item, index in scope.row.attr_vals" :ket="index" closable @close="removeTag(scope.row, index
                        )">
                            {{ item }}
                        </el-tag>
                        <el-input v-if="scope.row.inputVisible" ref="InputRef2" v-model="scope.row.inputValue"
                            class="w-1 m-1" size="small" @keyup.enter="handleInputConfirm(scope.row)"
                            @blur="handleInputConfirm(scope.row)" />
                        <el-button v-else class="m-1" size="small" @click="showInput2(scope.row)">
                            + New Tag
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="index" label="#" width="180" />
                <el-table-column prop="attr_name" label="属性名称" />
                <el-table-column>
                    <template #default="scope">
                        <el-button type="primary" :icon="EditOutlined" size="small"
                            @click="editshow(scope.row)">编辑</el-button>
                        <el-button type="danger" :icon="DeleteOutlined" size="small"
                            @click="del(scope.row.attr_id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-tab-pane>
    </el-tabs>


    <!-- 添加对话框 -->
    <el-dialog v-model="addFormVisible" :title="'添加' + addFormTitle" @closed="addFormClosed">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef">
            <el-form-item :label="addFormTitle" :label-width="formLabelWidth" prop="addParams">
                <el-input v-model="addForm.addParams" autocomplete="off" />
            </el-form-item>

        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="submitAddForm(addFormRef)">提交</el-button>
                <el-button @click="resetAddForm(addFormRef)">
                    重置
                </el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 编辑 -->
    <el-dialog v-model="editdialogFormVisible" :title="'编辑' + addFormTitle" @closed="editFormClosed">
        <el-form :model="editForm" :rules="editrules" ref="EditFormRef">
            <el-form-item :label="addFormTitle" :label-width="formLabelWidth" prop="editParams">
                <el-input v-model="editForm.editParams" autocomplete="off" />
            </el-form-item>

        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="submitEditForm(EditFormRef)">提交</el-button>
                <el-button @click="resetEditForm(EditFormRef)">
                    重置
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, onBeforeMount, computed, reactive, nextTick } from 'vue'
import axios from '../../axios';
import { DeleteOutlined, EditOutlined } from '@ant-design/icons-vue';
import { ElMessage } from 'element-plus';

const cat_info = ref([])
const options = ref([])
const props = {
    expandTrigger: 'hover',
    value: 'cat_id',
    label: 'cat_name',
}
const cate_id = ref()
const tableData = ref([])

const handleClick = (tab, event) => {
    nextTick(()=>{
        console.log(tab, event)
        getParams();
    })

}
const handleChange = (value) => {
    // console.log(cat_info._rawValue);
    if (value == null || cat_info.value.length !== 3) {
        cat_info.value = []
        tableData.value = []
        return
    }

    getParams();
}

const getCateList = async () => {
    const { data: res } = await axios.get(`categories`)
    if (res.meta.status !== 200) return
    options.value = res.data
    console.log(options.value)
}

onBeforeMount(() => {
    getCateList();
})

const activeName = ref('many')


const btnDisabled = computed(() => cat_info.value == null || cat_info.value.length !== 3)


const getParams = async () => {
    console.log(cat_info._rawValue[2], activeName.value)
    const { data: res } = await axios.get(`categories/${cat_info._rawValue[2]}/attributes`, { params: { sel: activeName.value } })
    console.log(res);
    if (res.meta.status !== 200) return
    tableData.value = res.data;
    tableData.value.forEach(ele => {
        ele.attr_vals = ele.attr_vals ? ele.attr_vals.split(',') : ''
    });
    console.log(tableData.value);
}


const addFormVisible = ref(false)
const addFormRef = ref(null)
const addForm = reactive({ addParams: '' })
const formLabelWidth = '140px'
const addFormRules = reactive({
    addParams: [{
        required: true, message: '必填', trigger: 'blur'
    }]
})

const submitAddForm = async (forEl) => {
    if (!forEl) return
    await forEl.validate(async (valid, fileds) => {
        if (valid) {
            const { data: res } = await axios.post(`categories/${cat_info._rawValue[2]}/attributes`, {
                attr_name: addForm.addParams,
                attr_sel: activeName.value
            })
            if (res.meta.status !== 201) return ElMessage.error('添加失败')
            ElMessage.success('添加成功')
            addFormVisible.value = false
            getParams()
        } else {
            console.log('error submit', fileds)
        }
    })
}
const resetAddForm = (formEL) => {
    if (!formEL) return
    formEL.resetFields();
}

const addFormClosed = () => {
    addForm.addParams = ''
}

const addFormTitle = computed(() => {
    if (activeName.value == 'many') return '动态参数'
    return '静态参数'
})

/* 编辑 */
const EditFormRef = ref(null)
const editdialogFormVisible = ref(false)
const editForm = reactive({ 
    editParams: '', 
    attr_vals:[]
})
const editrules = reactive({
    editParams: [
        { required: true, message: '该项是必填项必填', trigger: 'blur'}
    ]
})
const editAttrId = ref({})
const submitEditForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate(async (valid, fileds) => {
        if (valid) {
            console.log(editAttrId.value);
            console.log(cat_info.value[2]);
            const { data: res } = await axios.put(`categories/${cat_info.value[2]}/attributes/${editAttrId.value}`, {
                attr_name: editForm.editParams,
                attr_sel: activeName.value,
                attr_vals: editForm.attr_vals.join()
            })
            console.log(res);
            if (res.meta.status != 200) return ElMessage.error("修改参数失败")
            ElMessage.success('修改参数成功')
            editdialogFormVisible.value = false
            getParams()
        } else {
            console.log('error submit', fileds)
        }
    })
}
const resetEditForm = (formEL) => {
    if (!formEL) return
    formEL.resetFields();
}

const editFormClosed = () => {
    editForm.editParams = ''
    editForm.attr_vals = []
}

const editshow = (attr) => {
    editdialogFormVisible.value = true
    editForm.editParams = attr.attr_name
    editForm.attr_vals = attr.attr_vals
    editAttrId.value = attr.attr_id
}

const del = async (attr_id) => {
    const { data: res } = await axios.delete(`categories/${cat_info._rawValue[2]}/attributes/${attr_id}`)
    ElMessage.success('删除参数成功')
    getParams()
}

const inputValue = ref('')
const inputVisible = ref(false)
const InputRef = ref(null)
const dynamicTags = ref([]);
const expArr = ref([])
const handleInputConfirm = async (row) => {
    if (!row.inputValue) {
        row.inputVisible = false
        row.inputValue = ''
    }
    let inputVal = row.inputValue.trim()//去除字符串头尾空格
    if (!inputVal) return
    if (!row.attr_vals) row.attr_vals = [inputVal]
    else row.attr_vals.push(inputVal)
    console.log(row);
    const { data: res } = await axios.put(`categories/${row.cat_id}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: activeName.value,
        attr_vals: row.attr_vals.join()
    })
    if (res.meta.status != 200) return ElMessage.error('修改失败')
    ElMessage.success('修改成功')
    row.inputVisible = false
    row.inputValue = ''
}


const showInput = (row) => {
    row.inputVisible = true
    console.log(InputRef);
    nextTick(() => [
        InputRef.value.input.focus()
    ])
}
const InputRef2 = ref(null)
const showInput2 = (row) => {
    row.inputVisible = true
    console.log(InputRef2);
    nextTick(() => [
        InputRef2.value.input.focus()
])
}
const expandchange = (row, expandedRows) => {
    expArr.value = []
    expandedRows.forEach(ele => expArr.value.push(ele.attr_id))
}

const removeTag = async (row, index) => {
    row.attr_vals.splice(index, 1)
    const { data: res } = await axios.delete(`categories/${row.cat_id}/attributes/${row.attr_id}`, {
        attr_name: row.atrr_name,
        attr_sel: activeName.value,
        attr_vals: row.attr_vals.join()
    })
    if (res.meta.status != 200) return ElMessage.error('删除失败')
    ElMessage.success('删除成功')
}







</script>
<style>
.cate_list {
    margin: 15px 0;
}

.el-tag {
    margin: 10px
}

.w-1 {
    width: 80px;
    margin: 10px;
}
.el-alert{
    bottom: 10px;
}
</style>